/** 
 * @Author: Admin
 * @Date:   2017-09-26 12:54:53
 * @Last Modified by:   Admin
 * @Last Modified time: 2018/4/16
 */
(function(flex){
	window.Flex = flex();
})(
	function(){
		'use strict';
		var init,flex;

		function init(wraper){
			if(wraper.length !== 2 || !wraper[1].match(/\./)){
				flex.console.consoleError('当前版本仅支持类名作为父级包裹元素！');
			}else {
				return flex.get( wraper[0],wraper[1].replace('.',''));
			}
		}

		function flexing(wraper){

			var flexChildren = []//保存flex包裹元素下的子元素
			var indexes=[];
			for ( var i = 0 ; i < wraper.length; i++){  //待解决的优化方案
					var temp = wraper[i].children.length;
					indexes.push(temp);//非空元素的位置
					if(!flexChildren[temp]){//为了将具有flex包裹元素下个数相同的子元素 保存在同一数组中；以便提高效率
						flexChildren[temp] = [];
					}
					wraper[i].children.parent = wraper[i];
					flexChildren[temp]= flexChildren[temp].concat(wraper[i].children);

			}
			indexes = flex.pureArray(indexes)
			var count = {};//保存遍历之后得属性集合；
			for( var j = 0 ; j < indexes.length; j++){//j
				for(var k = 0; k < flexChildren[ indexes[j] ].length + 1 ; k++){// indexes[j]即为 flexChildren 里边不为空的元素的索引
					// flexChildren[indexes[j]][k].style.display = 'inline-block'
					var temp = 0;
					if( flexChildren[ indexes[j] ][k] ){
						flexChildren[ indexes[j] ][k].parent.style.whiteSpace='nowrap';
						flex.setLineHeight( flexChildren[ indexes[j] ][k].parent );//设置行高模拟 flex对齐效果；
						flexChildren[ indexes[j] ][k].parent.style.fontSize = 0;
						var parentWidth = parseFloat(flexChildren[ indexes[j] ][k].parent.clientWidth);
					}
					for( var z = 0; z < indexes[j] ;z++){
						if( flexChildren[ indexes[j] ][k] ){//
							if( flexChildren[ indexes[j] ][k][z].getAttribute('flex') == null){
								var cssText =
									"display:inline-block;"+
									"float:none;"+
									"white-space:normal;"+
									"line-height:normal;"+
									"vertical-align:middle;"
								;

								flexChildren[ indexes[j] ][k][z].style.cssText += ';'+ cssText;// 神奇的ie8不加分号会报错，即使cssText为 ''

								parentWidth = flex.normallizeWidth( parentWidth,flexChildren[ indexes[j] ][k][z])
								if(k !== 0){//操作当前项时对前一项进行百分比化；
									if(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex') && flexChildren[ indexes[j] ][k-1][z].getAttribute('flex').match(/^[\d]+\.*[\d]*$/)){
										flexChildren[ indexes[j] ][k-1][z].style.width = (parseFloat(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex')) / count['flexItems'+(k-1)])*count['parentWidth'+(k-1)]+'px';
										flex.reSetWidth(flexChildren[ indexes[j] ][k-1][z])
									}
									// flexChildren[ indexes[j] ][k-1][z].style.width = parseInt(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex')) / count['flexItems'+(k-1)]+'%';
								}
							}else if(flexChildren[ indexes[j] ][k][z].getAttribute('flex').match('px')){
								var cssText =
									"display:inline-block;"+
									"float:none;"+
									"white-space:normal;"+
									"line-height:normal;"+
									"vertical-align:middle;"+
									"width:" + flexChildren[ indexes[j] ][k][z].getAttribute('flex') + ';';
								;

								flexChildren[ indexes[j] ][k][z].style.cssText += ';'+ cssText

								parentWidth = flex.normallizeWidth( parentWidth,flexChildren[ indexes[j] ][k][z])
								if(k !== 0){//操作当前项时对前一项进行百分比化；
									if(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex') && flexChildren[ indexes[j] ][k-1][z].getAttribute('flex').match(/^[\d]+\.*[\d]*$/)){
										flexChildren[ indexes[j] ][k-1][z].style.width = (parseFloat(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex')) / count['flexItems'+(k-1)])*count['parentWidth'+(k-1)]+'px';
										flex.reSetWidth(flexChildren[ indexes[j] ][k-1][z])
									}
								}
							}else{
								var cssText =
									"display:inline-block;"+
									"float:none;"+
									"white-space:normal;"+
									"line-height:normal;"+
									"vertical-align:middle;"
								;

								flexChildren[ indexes[j] ][k][z].style.cssText += ';'+ cssText;
								temp += parseFloat(flexChildren[ indexes[j] ][k][z].getAttribute('flex'));
								if(k !== 0){//操作当前项时对前一项进行百分比化；
									if(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex') && flexChildren[ indexes[j] ][k-1][z].getAttribute('flex').match(/^[\d]+\.*[\d]*$/)){
										flexChildren[ indexes[j] ][k-1][z].style.width = (parseFloat(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex')) / count['flexItems'+(k-1)])*count['parentWidth'+(k-1)]+'px';
										flex.reSetWidth(flexChildren[ indexes[j] ][k-1][z])
									}
								}
							}

						}else if(flexChildren[ indexes[j] ][k-1]){//最后一个

							if(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex') && flexChildren[ indexes[j] ][k-1][z].getAttribute('flex').match(/^[\d]+\.*[\d]*$/)){
								flexChildren[ indexes[j] ][k-1][z].style.width = (parseFloat(flexChildren[ indexes[j] ][k-1][z].getAttribute('flex')) / count['flexItems'+(k-1)])*
									count['parentWidth'+(k-1)]+'px';
								flex.reSetWidth( flexChildren[ indexes[j] ][k-1][z] );//修正
							}
						}
					}
					count['flexItems'+k] = temp;//每次遍历第二层循环时 里边数组得长度都是相等得，因此遍历index非零得第一个元素时，可以操作已经遍历完成之后前一个得操作；
					count['parentWidth'+k] = parentWidth;
				}
			}

			// var count = {};  //另外一种方案
			// for ( var i = 0 ; i < wraper.length; i++){
			// 	var temp = 0;
			// 	for ( var j = 0 ; j < wraper[i].children.length; j++){
			// 		var parentWidth = wraper[i].clientWidth;
			// 		if(wraper[i].children[j]){

			// 			wraper[i].children[j].style.display = 'inline-block';

			// 			if( wraper[i].children[j].getAttribute('flex') == null){
			// 				parentWidth -= parseInt(wraper[i].children[j].offsetWidth);
			// 			}else if(wraper[i].children[j].getAttribute('flex').match('px')){
			// 				parentWidth -= parseInt(wraper[i].children[j].getAttribute('flex'))
			// 				wraper[i].children[j].style.width = wraper[i].children[j].getAttribute('flex');
			// 			}else{
			// 				console.log(wraper[i].children[j].clientWidth)
			// 				console.log(wraper[i].children[j].offsetWidth)
			// 				temp += parseInt(wraper[i].children[j].getAttribute('flex'));
			// 				if(i !== 0){//操作当前项时对前一项进行百分比化；
			// 					count['parent'+(i-1)]
			// 				}
			// 			}
			// 		}

			// 	}
				// count['parent'+i] = temp;
				// count['parentWidth'+i] = parentWidth;
				// console.log(count)

			// }

		}
		flex.prototype.init = init;
		flex.prototype.flexing = flexing;


		function flex(){
			var wraper = this.init(arguments);
			this.flexing(wraper);
		}

		flex.console = {
			consoleError:function(msg){
				console.log('%c'+msg,"color:red")
			}
		}
		flex.get = document.getElementsByClassName ?
		function(tag,cls){
			var temp =  document.getElementsByClassName(cls),result = [];
			for (var i = 0 ; i < temp.length; i++){
				// console.log(temp[i].tagName)
				if( temp[i].tagName.toLowerCase() == tag ){
					result.push(temp[i])
				}
			}
			return result;
		} :
		function(tag,cls) {
		var result = [];
		if ( tag == null )
				tag = '*';
		var els = document.getElementsByTagName(tag);
		var elsLen = els.length;
		for ( i = 0, j = 0; i < elsLen; i++) {

				if ( els[i].className.match(cls) ) {
						result[j] = els[i];
						j++;
				}
		}
		return result;
			}
		flex.pureArray = function(arr){//数组去重,都为简单类型所以采取这种办法，
			var result = [],temp = {};
			for( var i = 0; i < arr.length; i++){
				if(temp[arr[i]] === undefined ){
					result.push(arr[i]);
					temp[arr[i]] = 'zilong';
				}else{
					continue;
				}
			}
			return result;
		}
		flex.getStyle = function(obj,prop){
			return window.getComputedStyle?
				window.getComputedStyle(obj,null)[prop] :
				obj.currentStyle[prop];
		}
		flex.reSetWidth = function(obj){
			var paddings = flex.normalize(flex.getStyle(obj,'padding').split(' ')) ,
				borders = flex.normalize(flex.getStyle(obj,'borderWidth').split(' ')),
				margins = flex.normalize(flex.getStyle(obj,'margin').split(' '));
				// if(
				// 	window.navigator.userAgent.match('MSIE') &&
				// 	window.navigator.userAgent.match(/MSIE\s{1}(\d+\.+\d*)/)[1] >= 8
				//  ){//ie 9+ 如果未设置paddings margins的值不会返回0px   parseFloat之后的结果是NaN
				// 	if( parseFloat(margins[1]) !==parseFloat(margins[1]) ){
				// 		margins[1] = 0;
				// 	}
				// 	if( parseFloat(margins[3]) !==parseFloat(margins[3]) ){
				// 		margins[3] = 0;
				// 	}
				// 	if( parseFloat(paddings[1]) !==parseFloat(paddings[1]) ){
				// 		paddings[1] = 0;
				// 	}
				// 	if( parseFloat(paddings[3]) !==parseFloat(paddings[3]) ){
				// 		paddings[3] = 0;
				// 	}
				// }

			obj.style.width  = Math.round(parseFloat(obj.style.width) - parseFloat(paddings[1]) - parseFloat(paddings[3])
							- parseFloat(borders[1]) - parseFloat(borders[3]) - parseFloat(margins[1]) - parseFloat(margins[3])) +'px';

			return obj;
		}

		//margin padding 规格化 ===> 就是变成四个值的意思
		flex.normalize = function(arr){
			for( var i = 0; i< arr.length; i++ ){//ie8 获取之后会显示auto
				if( parseFloat(arr[i]) !==parseFloat(arr[i]) ){
					arr[i] = 0;
				}
			}
			switch( arr.length ){
				case 1:
					for( var i = 0; i < 3;i++ ){
						arr.push(arr[0])
					};
					break;
				case 2:
					arr[2] = arr[0];
					arr[3] = arr[1];
					break;
				case 3:
					arr[3] = arr[1];
					break;
				default:
					flex.console.consoleError( '发生了什么！！！' );
					break;
			}
			return arr;
		}

		//父元素宽度计算修正
		flex.normallizeWidth = function(pWidth , child){

			var margins = flex.normalize(flex.getStyle(child,'margin').split(' '));

			pWidth -= (Math.round( child.offsetWidth )+parseFloat(margins[1]) + parseFloat(margins[3]))//浏览器渲染是四舍五入
			return (pWidth);

		}
		// 设置line-height 以方便子元素使用vertical-align
		flex.setLineHeight = function(obj){
			var paddings =  flex.normalize(flex.getStyle(obj,'padding').split(' '));

			obj.style['height'] = obj.clientHeight - parseFloat(paddings[0]) - parseFloat(paddings[2]) + 'px';
			obj.style['lineHeight'] = parseFloat(obj.style['height']) - (-parseFloat(paddings[0])) - (-parseFloat(paddings[2])) + 'px';

		}
		//验证当前浏览器是否支持flex
		flex.validate = function(){
			return !(document.createElement('div').style['flex'] === undefined && document.createElement('div').style['msFlex'] === undefined );
		}
		if( flex.validate('support') ){
			console.log('您的浏览器支持flex布局，请使用flex');
			return function(){ console.log("%u4F60%u5C31%u5F53%u8FD9%u4E2A%u662F%u5F69%u86CB%u5427") };
		}
		return flex;
	}
)
